package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务接口实现类
 * @author wangxin
 * @version 1.0
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService
{

    @Autowired
    private UserDao userDao;

    /**
     * 根据用户名查询数据用户信息
     * @param username
     * @return
     */
    @Override
    public User findByUserName(String username) {
        return userDao.findByUserName(username);
    }


    //用户分页查询
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        //2.需要分页的语句
        Page<User> users = userDao.selectByCondition(queryString);
        return new PageResult(users.getTotal(), users.getResult());
    }

    //密码加密
    public String passwordEncryption(String password){
        if (password != null && password.length() > 0) {
            return new BCryptPasswordEncoder().encode(password);
        }
        return null;
    }

    //添加用户
    @Override
    public void add(User user, Integer[] roleMessage) {
        //密码加密
        user.setPassword(passwordEncryption(user.getPassword()));
        //往检查组表新增一条记录
        userDao.add(user);
        //往检查组和检查项中间表写记录(此方法有其它功能用 代码抽取)
        setUserAndRole(user.getId(),roleMessage);
    }

    //设置用户与角色的关系
    public void setUserAndRole(Integer id,Integer[] roleMessage){
        if(roleMessage != null && roleMessage.length> 0){
            for (Integer roleId : roleMessage) {
                //为了方便测试传入map对象
                Map<String,Integer> map = new HashMap<>();
                map.put("userId",id);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    //根据用户id查询角色关系
    @Override
    public List<Integer> findRoleIdsByUser(Integer userId) {
        return userDao.findRoleIdsByUser(userId);
    }

    //根据用户id查询用户
    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }

    //编辑用户
    @Override
    public void edit(User user, Integer[] roleMessage) {
        //密码加密
        user.setPassword(passwordEncryption(user.getPassword()));
        //更新用户表 update 语句
        userDao.edit(user);
        //先删除用户关联的角色记录 （中间表）
        userDao.deleteAssociation(user.getId());
        // 重新建立关联关系（插入中间表）
        setUserAndRole(user.getId(),roleMessage);
    }

    //删除用户
    @Override
    public void deleteById(Integer id) {
        userDao.deleteAssociation(id);
        userDao.deleteById(id);
    }
}
